package com.llsydn.demo.sqliteBl;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lilinshen
 * @title 黑名单Dao类black_number
 * @description 请填写相关描述
 * @date 2018/9/26 11:52
 */
public class BlackNumberDao {
    private DBHelper dbHelper;

    public BlackNumberDao(Context context) {
        this.dbHelper = new DBHelper(context);
    }

    /**
     * 添加一条记录
     *
     * @param blackNumber
     */
    public void add(BlackNumber blackNumber) {
        //1.得到连接
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        //2.执行insert
        ContentValues values = new ContentValues();
        values.put("number", blackNumber.getNumber());
        Long id = database.insert("black_number", null, values);
        blackNumber.setId(Integer.parseInt(String.valueOf(id)));
        Log.e("TAG", "id=" + id);
        //3.关闭连接
        database.close();
    }

    /**
     * 删除一条记录
     *
     * @param id
     */
    public void deleteById(int id) {
        //1.得到连接
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        //2.执行delete
        int deleteCount = database.delete("black_number", "_id=?", new String[]{id + ""});
        Log.e("TAG", "deleteCount=" + deleteCount);
        //3.关闭连接
        database.close();
    }

    /**
     * 更新一条记录
     *
     * @param blackNumber
     */
    public void update(BlackNumber blackNumber) {
        //1.得到连接
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        //2.执行update
        ContentValues values = new ContentValues();
        values.put("number", blackNumber.getNumber());
        int updateCount = database.update("black_number", values, "_id=" + blackNumber.getId(), null);
        Log.e("TAG", "updateCount=" + updateCount);
        //3.关闭连接
        database.close();
    }

    /**
     * 查询所有记录，封装成List<BlackNumber>
     */
    public List<BlackNumber> getAll() {
        List<BlackNumber> list = new ArrayList<BlackNumber>();
        //1.得到连接
        SQLiteDatabase database = dbHelper.getReadableDatabase();
        //2.执行query
        Cursor cursor = database.query("black_number", null, null, null, null, null, "_id desc", null);
        while (cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String number = cursor.getString(1);
            BlackNumber blackNumber = new BlackNumber(id, number);
            list.add(blackNumber);
        }
        Log.e("TAG", "count=" + cursor.getCount());
        //3.关闭连接
        cursor.close();
        database.close();
        return list;
    }
}
